
import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Alert,
    FlatList,
    TextInput,
    Linking,
    Image,
    DeviceEventEmitter,
    ScrollView,
    ImageBackground, PermissionsAndroid, KeyboardAvoidingView
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import { getImgUrl, getMileFormat } from '../../utils/ComFunction'
import Header from "../../components/header";
import ActionSheet from 'react-native-actionsheet'
import Upload from '../../components/upload/Upload'
import ImageCropPicker from 'react-native-image-crop-picker';

const isIos = Platform.OS == 'ios';

const screenW = Dimensions.get('window').width;

let questionMaxLength = 500

let imageContainerWidth = screenW - 8 * 2 - 16 * 2

// x*imageWidth+(x-1)*imageSpace <= imageContainerWidth
// x*(imageWidth+imageSpace) <= (imageContainerWidth+imageSpace)
// x <= (imageContainerWidth+imageSpace)/(imageWidth+imageSpace)
// x = Math.floor((imageContainerWidth+imageSpace)/(imageWidth+imageSpace))

let maxPicNumber = 5 //最多上传5张图片
let uploadingPicNumber = 0 //正在上传的图片数量
let uploadingPicIndex = 0 //正在上传的图片数量下标


let imageWidth = 60
let imageSpace = 8
//一行有多少个
let picNumberOfLine = Math.floor((imageContainerWidth + imageSpace) / (imageWidth + imageSpace))
//新的行间距
let newImageSpace = Math.floor((imageContainerWidth - picNumberOfLine * imageWidth) / (picNumberOfLine - 1))

let navigation

export default class ApplySaleServiceSubmitPage extends Component {
    constructor(props) {
        super(props);
        let serviceType = this.props.route.params.serviceType
        this.state = {
            serviceType: serviceType,
            afterSalesType: serviceType == 0 ? 1 : 2,
            questionType: this.props.route.params.questionType,
            questionTypeIndex: this.props.route.params.questionTypeIndex,

            carPrice: '',
            showBubble: false,
            question: '',
            carPics: [],
            orderNo: this.props.route.params.orderNo,
            orderInfo: {},

            finalTradePrice: '',
            detectionFee: '',
            advancePayment: '',
            refundAmount: '',
            tailPayment: '',
            finalPurchasePrice: '',

            receiveAccountId: '',
            receiveBankName: '',
            receiveBankAccount: '',
            receiveAccountName: '',
            isRefund: '',
            totalRefundAmount: ''
        }
        this.handleActionDebounced = this.debounce(this.handleAction, 1500);
    }

    componentDidMount() {
        this.getOrderDetail()
        // this.getDefaultBank()
        if (this.state.serviceType == 1) {
            this.afterSalesCalculateAmount()
        }
    }

    render() {
        navigation = this.props.navigation;
        let behavior = Platform.OS == 'ios' ? 'padding' : 'height';
        return (
            <KeyboardAvoidingView style={styles.container} behavior={behavior}>
                <Header navigation={navigation} hideSepLine={true} Title={'申请售后'} ></Header>
                <ScrollView style={{ flex: 1, paddingHorizontal: 8 }} showsVerticalScrollIndicator={false}>
                    <View style={styles.carBox}>
                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                            <Text style={styles.applyTitleText}>申请车辆</Text>
                            <TouchableOpacity
                                style={{ flexDirection: 'row', alignItems: 'center' }}
                            >
                                <Image style={styles.storeImg} source={require('source/image/store_icon.png')} />
                                <Text style={styles.storeText}>{this.state.orderInfo.sellerMerchantAbbreviation}</Text>
                            </TouchableOpacity>
                        </View>
                        <TouchableOpacity
                            activeOpacity={0.6}
                            style={styles.carInfoBox}
                            onPress={() => {

                            }}
                        >
                            <Image style={styles.carImg} source={{ uri: getImgUrl(this.state.orderInfo.mainPic) }} />
                            <View style={styles.carInfoRightBox}>
                                <Text style={styles.brandText}>{this.state.orderInfo.carName ? this.state.orderInfo.carName.replaceAll('#', ' ') : ''}</Text>
                                <Text style={styles.carInfoText}>{this.getSubCarInfo(this.state.orderInfo)}</Text>
                                <Text style={styles.priceInfoText}>{'成交价 ' + (this.state.orderInfo.quotationAmount / (100 * 10000))}万元</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={[styles.serviceTypeBox, { paddingBottom: this.state.serviceType == 0 ? 14 : 0 }]}>
                        <Text style={styles.applyTitleText}>售后信息</Text>
                        <View style={[styles.serviceTypeItemBox, { marginTop: 7 }]}>
                            <Text style={styles.serviceText}>售后原因<Text style={{ color: '#ED542E' }}>*</Text></Text>
                            <Text style={styles.serviceText}>{this.state.questionType}</Text>
                        </View>
                        {
                            this.state.serviceType == 0 ?
                                <View style={styles.serviceTypeItemBox}>
                                    <Text style={styles.serviceText}>{'车辆成交价'}<Text style={{ color: '#ED542E' }}>*</Text></Text>
                                    <View style={styles.serviceTypeRightItemBox}>
                                        <TextInput
                                            keyboardType={'decimal-pad'}
                                            autoCorrect={false}
                                            returnKeyType='done'
                                            autoCapitalize='characters'
                                            style={styles.textInput}
                                            editable={!this.props.disable}
                                            placeholder={'请输入与卖车达成一致的最终价格'}
                                            placeholderTextColor="#999999"
                                            value={this.state.carPrice}
                                            onChangeText={this.changeText.bind(this, 'carPrice')}


                                        />
                                        <Text style={styles.serviceText}>元</Text>
                                    </View>
                                </View>
                                :
                                <View style={styles.serviceTypeItemBox}>
                                    <Text style={styles.serviceText}>退车方式<Text style={{ color: '#ED542E' }}>*</Text></Text>
                                    <Text style={styles.serviceText}>上门取车</Text>
                                </View>
                        }

                        {this.state.serviceType == 0 ?
                            <View style={[styles.serviceTypeItemBox]}>
                                <Text style={styles.serviceText}>订单终价</Text>
                                <Text style={styles.serviceText}>{this.state.finalTradePrice / 100}元</Text>
                            </View>

                            : null
                        }


                        {
                            this.state.serviceType == 0 ?
                                <View style={styles.feeBox}>
                                    <View style={styles.feeItemBox}>
                                        <Text style={styles.feeTitleText}>车辆成交价</Text>
                                        <Text style={styles.feeDesText}>{this.state.finalPurchasePrice / 100}元</Text>
                                    </View>
                                    <View style={styles.feeItemBox}>
                                        <Text style={styles.feeTitleText}>门店服务费</Text>
                                        <Text style={styles.feeDesText}>{this.state.detectionFee / 100}元</Text>
                                    </View>
                                    <View style={styles.feeItemBox}>
                                        <Text style={styles.feeTitleText}>已预付</Text>
                                        <Text style={styles.feeDesText}>{this.state.advancePayment != '' ? '-' + this.state.advancePayment / 100 : '0'}元</Text>
                                    </View>

                                    {this.state.refundAmount && this.state.refundAmount != '' ?
                                        null
                                        :
                                        <View style={styles.feeItemBox}>
                                            <Text style={styles.feeTitleText}>尾款</Text>
                                            <Text style={styles.feeDesText}>{this.state.tailPayment / 100}元</Text>
                                        </View>
                                    }

                                    {
                                        this.state.showBubble ?
                                            <ImageBackground style={styles.bubbleImg} source={require('source/image/message_bubble.png')}>
                                                <Text style={styles.bubbleText}>门店账户默认银行卡收款</Text>
                                            </ImageBackground>
                                            :
                                            null
                                    }



                                </View>
                                :
                                null
                        }

                        <View style={[styles.serviceTypeItemBox, { marginTop: 7 }]}>
                            <Text style={styles.serviceText}>订单应退总额</Text>
                            <Text style={styles.serviceText}>{this.state.totalRefundAmount / 100}元</Text>
                        </View>

                        {this.state.refundAmount ?

                            <View style={[styles.serviceTypeItemBox, { marginTop: 7 }]}>
                                <Text style={styles.serviceText}>卖家应退总额<Text style={{ color: '#ED542E' }}>*</Text></Text>
                                <Text style={styles.serviceText}>{this.state.refundAmount ? this.state.refundAmount / 100 : '0'}元</Text>
                            </View>
                            : null
                        }


                        {/* {this.state.refundAmount && this.state.refundAmount != '' ?
                            <TouchableOpacity style={[styles.serviceTypeItemBox, { marginTop: 7 }]}
                                onPress={() => {
                                    navigation.navigate('BankCardSelectPage', {
                                        selectedCardId: '', completion: (result) => {
                                            this.setState({
                                                receiveBankName: result.accountBank,
                                                receiveBankAccount: result.accountNo,
                                                receiveAccountName: result.accountName,
                                                receiveAccountId: result.id
                                            })
                                        }
                                    })
                                }}>
                                <Text style={styles.serviceText}>收款账户<Text style={{ color: '#ED542E' }}>*</Text></Text>

                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    <Text style={styles.serviceText} numberOfLines={1} ellipsizeMode={'tail'}>{this.state.receiveBankName + this.state.receiveBankAccount}</Text>
                                    <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />

                                </View>

                            </TouchableOpacity>
                            : null
                        } */}

                    </View>

                    <View style={styles.serviceTypeBox}>
                        <Text style={styles.applyTitleText}>问题描述<Text style={{ color: '#ED542E' }}>*</Text></Text>
                        <View style={styles.desBox}>
                            <TextInput
                                clearButtonMode='while-editing'
                                maxLength={questionMaxLength}
                                style={styles.questionTextInput}
                                placeholder='请详细描述你遇到的问题，最多500字'
                                multiline={true}
                                placeholderTextColor="#999999"
                                value={this.state.question}
                                lineHeight={20}
                                onChangeText={this.changeText.bind(this, 'question')}
                            />
                            <Text style={styles.questionCountText}>{this.state.question.length + '/' + questionMaxLength}</Text>
                        </View>
                    </View>

                    <View style={[styles.serviceTypeBox, { paddingBottom: 0 }]}>
                        <Text style={styles.applyTitleText}>请上传问题车辆照片(最多5张)</Text>
                        <View style={styles.imgContainer}>
                            {
                                this.state.carPics.map((item, index) => {
                                    return (
                                        <Image key={index} style={[styles.carUploadImg, { marginBottom: newImageSpace, marginLeft: index % picNumberOfLine != 0 ? newImageSpace : 0 }]} source={{ uri: getImgUrl(item) }} />
                                    )
                                })
                            }
                            {
                                this.state.carPics.length < maxPicNumber ?
                                    <TouchableOpacity
                                        style={[styles.carUploadImg, { marginBottom: newImageSpace, marginLeft: this.state.carPics.length % picNumberOfLine != 0 ? newImageSpace : 0 }]}
                                        onPress={() => {
                                            this.ActionSheet.show()
                                        }}
                                    >
                                        <Image style={styles.carUploadImg} source={require('source/image/add_img_icon.png')} />
                                    </TouchableOpacity>
                                    :
                                    null
                            }
                        </View>
                    </View>

                    <View style={{ height: 10 }} />

                    <View style={[styles.bottomBox, { height: 60 + Constant.bottomHeight }]}>
                        <TouchableOpacity
                            style={styles.submitBox}
                            activeOpacity={0.8}
                            onPress={() => {
                                this.submit()
                            }}
                        >
                            <Text style={styles.submitText}>提交</Text>
                        </TouchableOpacity>
                    </View>


                </ScrollView>



                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片来源 ?'}
                    options={['相册', '拍照', '取消']}
                    cancelButtonIndex={2}
                    onPress={(index) => { this.selectPhoto(index) }}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </KeyboardAvoidingView>
        )
    }



    getSubCarInfo(item) {

        let carInfoStr = ''
        if (item.registerDate && item.registerDate != null) {


            carInfoStr = moment(item.registerDate).format('YYYY-MM')
        }

        if (item.mileage && item.mileage != 0) {
            carInfoStr = carInfoStr + ' | ' + getMileFormat(item.mileage)
        }

        if (item.sellerUserCityName && item.sellerUserCityName != '') {
            if (carInfoStr != '') {
                carInfoStr = carInfoStr + ' | ' + item.sellerUserCityName
            } else {
                carInfoStr = item.sellerUserCityName
            }

        }

        return carInfoStr
    }


    //选择相册还是照相机
    selectPhoto(index) {
        if (index == 0) {
            //相册
            const option = {
                mediaType: "photo",
                cropping: false,
                compressImageQuality: .9,
                multiple: true,
                maxFiles: maxPicNumber - this.state.carPics.length
            };
            ImageCropPicker.openPicker(option).then(images => {
                console.log('images = ', images)
                if (this.Loading) {
                    this.Loading.show('正在上传...');
                }
                uploadingPicNumber = images.length
                uploadingPicIndex = 0
                images.map((item) => {
                    Upload.getAlipz(item.path, Upload.ossTypeImage, this.uploadafterfun);//获取阿里凭证。
                })
            }, (error) => {
                // alert(error);
            });

        } else if (index == 1) {
            //照相机
            this.openCamera();
        }
    }

    openCamera() {
        if (isIos) {
            this.takePhoto()
        } else {
            PermissionsAndroid.check('android.permission.CAMERA').then(res => {
                if (!res) {
                    this.setDialogVisible(true)
                }
                else {
                    this.takePhoto()
                }
            })
        }
    }

    takePhoto() {
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .6, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openCamera(option).then(images => {
            if (this.Loading) {
                this.Loading.show('正在上传...')
            }
            uploadingPicNumber = 1
            uploadingPicIndex = 0
            Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            // alert(error);
        });
    }

    // 上传图片成功后 回调
    uploadafterfun = (picUrl) => {
        uploadingPicIndex++
        let pics = this.state.carPics
        pics.push(picUrl)
        this.setState({
            pics: pics
        }, function () {
            if (uploadingPicIndex == uploadingPicNumber) {
                if (this.Loading) {
                    this.Loading.hide();
                }
            }
        })
    }

    //输入框内容输入
    changeText(type, val) {
        this.setState({
            [type]: val
        })

        if (type == 'carPrice') {
            this.handleActionDebounced(val);
        }

    }

    handleAction = (text) => {
        this.afterSalesCalculateAmount();
    };

    debounce(func, delay = 1500) {
        let timer = null;
        return function (...args) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(this, args);
            }, delay);
        };
    }

    getOrderDetail() {

        let param = {

            orderNo: this.state.orderNo
        }

        HttpUtils.getRequest(HttpUrls.getDetailsByOrderNo, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0 && result.data) {
                    this.setState({
                        orderInfo: result.data,

                    })



                }

            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getDefaultBank() {

        let param = {

            merchantId: Constant.userInfo.merchantId
        }

        HttpUtils.getRequest(HttpUrls.getDefaultBank, param)
            .then((result) => {

                if (result.code == 0 && result.data) {
                    this.setState({
                        bankInfo: result.data,

                    })

                }

            })
            .catch((error) => {

            });
    }

    afterSalesCalculateAmount() {

        let param = {

            quotationOrderNo: this.state.orderNo,
            afterSalesType: this.state.afterSalesType,

        }
        if (this.state.serviceType == 0) {
            let finalPurchasePrice = parseFloat(this.state.carPrice) * 100;
            param['finalPurchasePrice'] = finalPurchasePrice
        } else {
            param['finalPurchasePrice'] = 0
        }

        HttpUtils.postRequest(HttpUrls.afterSalesCalculateAmount, param)
            .then((result) => {

                if (result.code == 0 && result.data) {

                    this.setState({
                        finalTradePrice: result.data.finalTradePrice,
                        detectionFee: result.data.detectionFee,
                        advancePayment: result.data.advancePayment,
                        refundAmount: result.data.refundAmount,
                        tailPayment: result.data.tailPayment,
                        finalPurchasePrice: result.data.finalPurchasePrice,
                        isRefund: result.data.isRefund,
                        totalRefundAmount: result.data.totalRefundAmount
                    })

                }

            })
            .catch((error) => {

            });
    }



    submit() {

        if (this.state.serviceType = 0 && this.state.carPrice == '') {
            ToastToUser('请输入最终修改价');
            return
        }

        if (this.state.question == '') {
            ToastToUser('请输入问题描述');
            return
        }

        // if (this.state.isRefund == 1 && this.state.receiveAccountId == '') {
        //     ToastToUser('请选择收款账户');
        //     return
        // }

        this.Loading.show()

        let finalPurchasePrice = parseFloat(this.state.carPrice) * 100;
        let carAbnormalPics = this.state.carPics.join(',');

        console.log('serviceType==', this.state.serviceType)
        let param = {

            quotationOrderNo: this.state.orderNo,
            afterSalesType: this.state.afterSalesType,
            finalPurchasePrice: finalPurchasePrice,
            afterSalesReason: this.state.questionTypeIndex,
            afterSalesRemark: this.state.question,
            carAbnormalPics: carAbnormalPics,

            receiveAccountId: this.state.receiveAccountId,
            receiveBankName: this.state.receiveBankName,
            receiveBankAccount: this.state.receiveBankAccount,
            receiveAccountName: this.state.receiveAccountName
        }

        // if (this.state.refundAmount && this.state.refundAmount != '') {
        //     param['receiveAccountId'] = this.state.receiveAccountId
        //     param['receiveBankName'] = this.state.receiveBankName
        //     param['receiveBankAccount'] = this.state.receiveBankAccount
        //     param['receiveAccountName'] = this.state.receiveAccountName
        // }

        HttpUtils.postRequest(HttpUrls.afterSalesApply, param)
            .then((result) => {
                if(this.Loading){
                    this.Loading.hide();
                }
                if (result.code == 0 && result.data) {
                    DeviceEventEmitter.emit('refreshOrderDetail', {})
                    navigation.replace('AfterSaleOrderDetail', { orderNo: result.data.afterSalesNo })

                }else{
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }

            })
            .catch((error) => {

            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    carBox: {
        marginTop: 10,
        width: '100%',
        height: 150,
        borderRadius: 6,
        backgroundColor: '#fff',
        paddingHorizontal: 16,
        paddingVertical: 12,
        flexDirection: 'column'
    },
    applyTitleText: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333'
    },
    storeImg: {
        width: 20,
        height: 20
    },
    storeText: {
        marginLeft: 3,
        fontSize: 12,
        color: '#333333'
    },
    carInfoBox: {
        marginTop: 14,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        width: '100%',
        height: 90,
    },
    carImg: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#F9F9F9'
    },
    carInfoRightBox: {
        marginLeft: 12,
        height: '100%',
        flex: 1,
        flexDirection: 'column',
        alignItems: 'flex-start'
    },
    brandText: {
        lineHeight: 20,
        fontSize: 14,
        fontWeight: '500',
        color: '#333333'
    },
    carInfoText: {
        marginTop: 4,
        lineHeight: 17,
        fontSize: 12,
        color: '#333'
    },
    priceInfoText: {
        position: 'absolute',
        bottom: 0,
        lineHeight: 20,
        fontSize: 14,
        color: '#333'
    },
    serviceTypeBox: {
        marginTop: 10,
        paddingHorizontal: 16,
        paddingVertical: 14,
        width: '100%',
        borderRadius: 6,
        backgroundColor: '#fff',
        flexDirection: 'column'
    },
    serviceTypeItemBox: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%',
        height: 45,
    },
    serviceText: {
        fontSize: 14,
        color: '#333'
    },
    servicePriceText: {
        fontSize: 14,
        fontWeight: '500',
        color: '#ED542E'
    },
    serviceTypeRightItemBox: {
        flexDirection: 'row',
        marginLeft: 20,
        height: '100%',
        flex: 1,
        justifyContent: 'flex-end',
        alignItems: 'center'
    },

    arrowImg: {
        marginLeft: 5,
        width: 16,
        height: 16
    },
    alertText: {
        marginTop: 12,
        fontSize: 14,
        color: '#ED542E',
        textAlign: 'center'
    },
    textInput: {
        paddingRight: 5,
        color: '#333333',
        fontSize: 14,
        height: '100%',
        flex: 1,
        height: '100%',
        textAlign: 'right'
    },
    feeBox: {
        backgroundColor: '#F4F4F4',
        borderRadius: 6,
        flexDirection: 'column',
        width: '100%'
    },
    feeItemBox: {
        width: '100%',
        paddingHorizontal: 16,
        height: 38,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    feeTitleText: {
        fontSize: 14,
        color: '#666666'
    },
    feeDesText: {
        fontSize: 14,
        fontWeight: '500',
        color: '#666666'
    },
    questionImg: {
        marginLeft: 3,
        width: 13,
        height: 13,
    },
    bubbleImg: {
        position: 'absolute',
        left: 58,
        bottom: 28,
        width: 150,
        height: 30
    },
    bubbleText: {
        fontSize: 12,
        color: '#333',
        marginLeft: 8,
        marginTop: 6,
    },
    desBox: {
        marginTop: 12,
        backgroundColor: '#F9F9F9',
        width: '100%',
        height: 123,
        borderRadius: 6
    },
    questionTextInput: {
        padding: 12,
        flex: 1,
        height: '100%',
        textAlignVertical: 'top',
        fontSize: 14
    },
    questionCountText: {
        position: 'absolute',
        right: 12,
        bottom: 12,
        color: '#333',
        fontSize: 12
    },
    imgContainer: {
        marginTop: 14,
        width: '100%',
        flex: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',

    },
    carUploadImg: {
        width: imageWidth,
        height: imageWidth,
        borderRadius: 6,
        backgroundColor: '#f9f9f9'
    },
    bottomBox: {
        width: '100%',
        backgroundColor: '#fff',

        paddingTop: 7,
        flexDirection: 'column',
        alignItems: 'center'
    },
    submitBox: {
        width: '100%',
        height: 46,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFE000',
        borderRadius: 23
    },
    submitText: {
        color: '#333333',
        fontSize: 16
    }
})